package pers.lx.crm.service.business.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.lx.crm.base.common.pigeon.Result;
import pers.lx.crm.base.constant.ErrorConstant;
import pers.lx.crm.base.constant.KeyConstants;
import pers.lx.crm.base.util.ResultUtil;
import pers.lx.crm.dao.business.BusinessDao;
import pers.lx.crm.entiy.business.BusinessDO;
import pers.lx.crm.entiy.business.BusinessFlowDO;
import pers.lx.crm.entiy.business.FlowDO;
import pers.lx.crm.service.business.BusinessService;

import java.util.List;

/**
 * Created by lxl on 2017/3/8.
 */
@Service
public class BusinessServiceImpl implements BusinessService{

    @Autowired
    private BusinessDao businessDao ;

    @Override
    public Result getBusinesses(BusinessDO businessDO) {
        Result result = new Result() ;
        try {
            businessDO.setList(businessDao.selectBusinessListPage(businessDO));
            return ResultUtil.getPageResult(businessDO,result) ;
        } catch (Exception e){
            e.printStackTrace();
            result.setError(ErrorConstant.UNKNOWN_ERROR);
        }
        return result;
    }

    @Transactional
    @Override
    public Result addBusiness(BusinessDO businessDO) {
        Result result = new Result() ;
        businessDao.insertBusiness(businessDO);
        for (BusinessFlowDO businessFlowDO:businessDO.getBusinessFlowDOs()){
            businessFlowDO.setBusinessId(businessDO.getId());
            businessDao.insertBusinessFlow(businessFlowDO);
        }
        return result;
    }

    @Transactional
    @Override
    public Result updateBusiness(BusinessDO businessDO) {
        Result result = new Result() ;
        businessDao.updateBusiness(businessDO);
        businessDao.deleteBusinessFlow(businessDO.getId());
        for (BusinessFlowDO businessFlowDO:businessDO.getBusinessFlowDOs()){
            businessFlowDO.setBusinessId(businessDO.getId());
            businessDao.insertBusinessFlow(businessFlowDO);
        }
        return result;
    }

    @Transactional
    @Override
    public Result removeBusinesses(List<BusinessDO> businessDOs) {
        Result result = new Result() ;
        for (BusinessDO businessDO:businessDOs){
            businessDao.deleteBusinessFlow(businessDO.getId());
            businessDao.deleteBusiness(businessDO);
        }
        return result;
    }

    @Override
    public Result getFlows(BusinessDO businessDO) {
        Result result = new Result() ;
        result.addParam(KeyConstants.LIST_KEY,businessDao.selectFlow(businessDO.getId()));
        return result;
    }
}
